package kaka 
{
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	import net.hires.debug.*;
	
	/**
	 * 四叉树研究测试
	 * @author StefanieKaka
	 */
	public final class QuadTreeMain extends Sprite 
	{
		
		public function QuadTreeMain() 
		{
			this.mouseEnabled = false;
			this.mouseChildren = false;
			
			m_qtree = new QuadTree(new Rectangle(0, 0, this.stage.stageWidth, this.stage.stageHeight));
			m_qtree.createChildren(4);
			
			for (var i : int = 0; i < 100; ++i)
			{
				var shape : Shape = new Shape();
				shape.graphics.lineStyle(1, 0x000000);
				shape.graphics.drawRect(0, 0, Math.random() * 100 + 20, Math.random() * 50 + 10);
				shape.x = Math.random() * this.stage.stageWidth;
				shape.y = Math.random() * this.stage.stageHeight;
				//shape.x = (this.stage.stageWidth - shape.width) / 2;
				//shape.y = (this.stage.stageHeight - shape.height) / 2;
				this.addChild(shape);
				
				//m_qtree.addPoint(shape, shape.x, shape.y);
				//m_qtree.removePoint(shape);
				
				m_qtree.addRect(shape, shape.getRect(this));
				//m_qtree.removeRect(shape, shape.getRect(this));
			}
			
			trace(m_qtree.order());
			
			this.stage.addEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
			
			this.addChild(new Stats());
		}
		
		private function onEnterFrameHandler(evt : Event) : void
		{
			var rect : Rectangle = null;
			var data : Vector.<*> = m_qtree.getDataInRect(new Rectangle(0, 0, this.stage.stageWidth, this.stage.stageHeight));
			for each (var s : Shape in data)
			{
				rect = s.getRect(this);
				s.graphics.clear();
				s.graphics.lineStyle(1, 0x000000);
				s.graphics.drawRect(0, 0, rect.width, rect.height);
			}
			
			// 绘制控制的矩形
			rect = new Rectangle(this.mouseX, this.mouseY, 100, 50);
			this.graphics.clear();
			this.graphics.beginFill(0x0000ff);
			this.graphics.drawRect(rect.x, rect.y, rect.width, rect.height);
			this.graphics.endFill();
			m_qtree.draw(this.graphics);
			
			// 碰撞检测
			data = m_qtree.getDataInRect(rect);
			trace(data.length);
			for each (s in data)
			{
				rect = s.getRect(this);
				s.graphics.clear();
				s.graphics.lineStyle(4, 0xff0000);
				s.graphics.drawRect(0, 0, rect.width, rect.height);
			}
		}
		
		private var m_qtree : QuadTree = null;
	}

}